package com.mock.ems.controller.cooperation;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.mock.base.util.BeanUtil;
import com.mock.base.util.StringUtil;
import com.mock.ems.bean.AreaAgent;
import com.mock.ems.common.JsonResult;

import java.util.*;

/**
 * Created by MOCK on 2017/8/3.
 */
public class AreaAgentController extends Controller {

    public void index() {
        renderJsp("/page/cooperation/areaagent/areaagent_list.jsp");
    }

    public void pagination() {
        int pageNumber = getParaToInt("pageNumber");
        int pageSize = getParaToInt("pageSize");

        StringBuilder exceptSelectSQL = new StringBuilder(" from area_agent where 1 = 1 ");
        List<Object> params = new ArrayList<Object>();

        String realName = getPara("real_name");
        if (StringUtil.isNotEmpty(realName)) {
            exceptSelectSQL.append(" and real_name like ?");
            params.add("%" + realName.trim() + "%");
        }

        String phone = getPara("phone");
        if (StringUtil.isNotEmpty(phone)) {
            exceptSelectSQL.append(" and phone = ?");
            params.add(phone.trim());
        }

        String address = getPara("address");
        if (StringUtil.isNotEmpty(address)) {
            exceptSelectSQL.append(" and address like ? ");
            params.add("%" + address.trim() + "%");
        }


        exceptSelectSQL.append(" order by update_time desc ");
        Page<Record> recordList = null;
        if (params.size() == 0) {
            recordList = Db.paginate(pageNumber, pageSize, "select * ", exceptSelectSQL.toString());
        }else {
            recordList = Db.paginate(pageNumber, pageSize, "select * ", exceptSelectSQL.toString(),params.toArray());
        }

        Map<String, Object> returnMap = new HashMap<String, Object>();
        returnMap.put("total", recordList.getTotalRow());
        returnMap.put("rows", recordList.getList());
        renderJson(returnMap);
    }

    public void edit() {

        Long id = getParaToLong("id");
        Record record = Db.findById("area_agent",id);

        if (null != record) {
            Long user_id = record.getLong("user_id");
            Record userRecord = Db.findById("user",user_id);
            if (null != userRecord) {
                record.set("user",userRecord.getColumns());
            }
            setAttr("areaAgent",record.getColumns());
        }
        renderJsp("/page/cooperation/areaagent/areaagent_edit.jsp");
    }

    @Before(Tx.class)
    public void save() {
        AreaAgent areaAgent = getBean(AreaAgent.class,"");
        JsonResult result = new JsonResult();
        Record record = new Record();
        try {
            record.setColumns(BeanUtil.objectToMap(areaAgent));
        } catch (Exception e) {
            renderJson(result.status("-1").show("保存失败"));
            return;
        }

        boolean success;
        if (areaAgent.getId() == null) {
            success = Db.save("area_agent",record);
        }else {
            Record areaAgentRecord = Db.findById("area_agent",areaAgent.getId());
            record.set("update_time",new Date());
            record.set("status",areaAgentRecord.get("status"));
            success = Db.update("area_agent",record);
        }

        if (success) {
            renderJson(result.status("000").show("保存成功"));
        }else {
            renderJson(result.status("-3").show("保存失败"));
        }
    }

    @Before(Tx.class)
    public void delete() {

        String areaAgentIdList = getPara("areaAgentIdList");
        JsonResult result = new JsonResult();
        if (StringUtil.isEmpty(areaAgentIdList)) {
            renderJson(result.status("001").show("删除失败"));
            return;
        }

        StringBuilder deleteSQL = new StringBuilder("delete from area_agent where id in (");
        Object [] areaAgents = new Object[areaAgentIdList.split(",").length];
        int index = 0;
        for (String id : areaAgentIdList.split(",")) {
            deleteSQL.append("?,");
            areaAgents[index]= id;
            index ++;
        }
        deleteSQL.deleteCharAt(deleteSQL.length() - 1).append(")");


        boolean deleteResult = Db.update(deleteSQL.toString(),areaAgents) == areaAgents.length;
        renderJson(deleteResult ? result.status("000").show("删除成功"):result.status("002").show("删除失败"));
    }

    /**
     * 激活
     */
    @Before(Tx.class)
    public void activate() {

        Long id = getParaToLong("id");
        Record areaAgentRecord = Db.findById("area_agent",id);
        areaAgentRecord.set("status",1);
        if (Db.update("area_agent",areaAgentRecord)) {
            Long userId = areaAgentRecord.getLong("user_id");
            Record user = Db.findById("user",userId);
            if (null != user) {
                String role = user.get("role");
                if (StringUtil.isNotEmpty(role) && role.indexOf("6") == -1) {
                    role += ",6";
                    user.set("role",role)
                            .set("update_time",new Date());
                    if (!Db.update("user",user)) {
                        throw new RuntimeException("update user role fail");
                    }
                }
            }
            renderJson(new JsonResult().status("000").show("激活成功"));
        }else {
            renderJson(new JsonResult().status("-1").show("激活失败"));
        }
    }

    /**
     * 冻结
     */
    @Before(Tx.class)
    public void freeze() {

        Long id = getParaToLong("id");
        Record areaAgent = Db.findById("area_agent",id);
        areaAgent.set("status",0);
        if (Db.update("area_agent",areaAgent)) {
            Long user_id = areaAgent.getLong("user_id");
            //更新用户角色为合作伙伴
            Record user = Db.findById("user",user_id);
            if (null !=user) {
                String role = user.get("role");
                if (StringUtil.isNotEmpty(role) && role.indexOf("6") != -1) {
                    role = role.replace(",6","");
                    user.set("role",role)
                            .set("update_time",new Date());
                    if (!Db.update("user",user)) {
                        throw new RuntimeException("update user role fail");
                    }
                }
            }
            renderJson(new JsonResult().status("000").show("冻结成功"));
        }else {
            renderJson(new JsonResult().status("-1").show("冻结失败"));
        }
    }

    public void search() {

        String searchName = getPara("searchName");
        Integer searchNew = getParaToInt("snew");
        if (null == searchNew) searchNew = 0;

        if (StringUtil.isEmpty(searchName)) {
            renderJson(new JsonResult().status("-1").show("请填写昵称或者手机号再进行搜索"));
            return;
        }
        String sql = "select id,nick_name,head_photo from user where nick_name like ? or phone like ? ";
        Record record = Db.findFirst(sql,'%' + searchName + '%','%' + searchName + '%');
        if (null == record) {
            renderJson(new JsonResult().status("-1").show("无法查找到记录，请检查内容是否填写正确。"));
            return;
        }

        if (searchNew == 0) {
            Long user_id = record.getLong("id");
            if (Db.findFirst("select id from area_agent where user_id = ? and status = 1",user_id) == null) {
                renderJson(new JsonResult().status("-1").show("未找到对应的区县代理"));
                return;
            }
        }

        //无需理会
        record.set("a","b");
        renderJson(new JsonResult().status("000").data(record.getColumns()));
    }
}
